/*
 * @Author: 
 * @Date: 2021-12-08 17:39:23
 * @LastEditors: lqj
 * @LastEditTime: 2022-02-28 11:53:20
 * @Description: 请填写简介
 */
/**
 * 生成children列表，添加层级
 * @param {array} arr
 * @param {number} num
 * @return {array}
*/
export function setPopChild(arr, num) {
  return arr.map(it => {
    if (it.children) {
      it.children = getList([], Math.random() * 20, it.code, it.code)
      if (it.code.toString().length < num) setPopChild(it.children, num - 1)
    }
    return it
  })
}
/**
 * 生成列表数据
 * @param {number} item
 * @return {array}
*/
export function getChildrenList(item) {
  return getList([], item, 1, 0).reduce((cur, val) => {
    val.children = getList([], Math.random() * 20, val.code, val.code)
    cur.push(val)
    return cur
  }, [])
}
// 数据结构
/**
 * @param { array } list 空列表
 * @param { number } num 列表条目
 * @param { number } key 标识id
 * @param { number } code 父级id
 * @return { array }
*/
export function getList(list, num, key, code) {
  for (let i = 0; i < num; i++) {
    list.push({
      children: [],
      name: `item-${key}-${i}`,
      code: Number(`${key}${i}`),
      checked: false,
      isIndeterminate: false,
      count: 0,
      parentCode: code,
      show: true
    })
  }
  return list
}

/**
 * 循环树形列表查找选中项
 * @param {boolean} val
 * @param {array} tree
 * @param {object} op
 * @param {string} op.code
*/
export function setTreeItem (val, tree, op) {
  for (let i = 0; i < tree.length; i++) {
    const it = tree[i]
    if (it.code === op.code) {
      it.checked = val
      it.isIndeterminate = false
    }
    if (it.children) setTreeItem(val, it.children, op)
  }
}

/**
 * 更新选中状态
 * @param {bool} flag
 * @param {object} item
 * @param {array} item.children
*/
export function changeChildItemsCheckedStatus (flag, item) {
  if (!item.children) return
  item.children = item.children.map(it => {
    if (it.children) {
      changeChildItemsCheckedStatus(flag, it)
    }
    return { ...it, checked: flag, isIndeterminate: false }
  })
}

/**
 * 计算已选项
 * @param {array} tree
 * @return {number}
*/
export function getCount (tree) {
  let total = 0
  tree.forEach(item => {
    let count = 0
    if (item.show && item.checked) count += 1
    if (item.children && item.children.length > 0) {
      count += getCount(item.children)
      if (item.checked) count -= 1
    }
    item.count = count
    total += count
  })
  return total
}

/**
 * 循环已选项
 * @param {array} tree
 * @param {string} tree
*/
export function checkedLinkBy (tree, code) {
  for (let i = 0; i < tree.length; i++) {
    if (tree[i].code === code) {
      changeChildItemsCheckedStatus(true, tree[i])
    } else {
      if (tree[i].children) {
        checkedLinkBy(tree[i].children, code)
      }
    }
  }
}